package cn.hls.dao.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.springframework.stereotype.Component;

import cn.hls.dao.ShipOrderGoodsDao;
import cn.hls.entity.ShipOrderGoods;
import cn.hls.exception.BussinessException;
import cn.hlsconstant.DataAssessEnum;

 
 
/**
  *@fileName: ShipOrderGoodsDaoImpl.java
  *@package: cn.hls.dao.impl
　*@Description:货物数据操作接口实现类
　*@author: uuhui@163.com
  *@date: 2016年6月9日
 *
 */
@Component("shipOrderGoodsDao")
public class ShipOrderGoodsDaoImpl extends BaseDaoImpl<ShipOrderGoods> implements ShipOrderGoodsDao {
	@Override
	public List<ShipOrderGoods> loadShipOrderGoodsList(ShipOrderGoods entity)throws Exception{
		// 定义查询Hql语句
		StringBuilder selectHql=new StringBuilder("from ShipOrderGoods p inner join fetch p.goods g left join fetch g.safetyCard sc  where p.deleted=? ");
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(false);
		if (entity != null) {
			//按运单编号查询
			 if(entity.getShipOrderId()!=null){
				 selectHql.append("and p.shipOrderId=? ");
				 paramList.add(entity.getShipOrderId());
			 }
			 //按货物编号查询
			 if(entity.getGoods()!=null ){
				 if(entity.getGoods().getId()!=null){
					 selectHql.append("and g.id=? ");
					 paramList.add(entity.getGoods().getId());
				 }
			 }
			 
		}
		return findByHql(selectHql.toString(), paramList.toArray());
	}

	@Override
	public void delete(Object shipOrderId) throws Exception {
		String hql="delete from ShipOrderGoods where shipOrderId=?";
		 
		 try {
			executeHQLUpdate(hql.toString(),new Object[]{shipOrderId});
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.DELETE_ERROR,"删除货物信息失败" );
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean exists(List<Long>shipOrderIdList,List<ShipOrderGoods>goodsList	)throws Exception{
		Map<Long,Long>map=new HashMap<Long, Long>();
		boolean resultFlag=false;//定义返回的结果
		for(ShipOrderGoods item:goodsList){
			if(item.getGoods()!=null && item.getGoods().getId()!=null){
				map.put(item.getGoods().getId(), item.getGoods().getId());
			}
		}
		for(Long shopOrderId:shipOrderIdList){
			StringBuilder selectHql=new StringBuilder("SELECT GOODS_ID FROM T_SHIPORDER_GOODS t where t.IS_DELETED=? and t.SHIPORDER_ID=? ");
			SQLQuery query =getSession().createSQLQuery(selectHql.toString());
			query.setParameter(0, false);
			query.setParameter(1, shopOrderId);
			List<BigDecimal>resultList=query.list();
			if(resultList.size()==map.size()){//判断两者的大小是否相同
				boolean flag=true;
				for(BigDecimal id:resultList){
					Long tempId=id.longValue();
					flag&=tempId.longValue()==map.get(tempId).longValue();
				}
				if(flag){
					resultFlag=flag;
					break;
				}
			}else{
				continue;
			}
		}
		return resultFlag;
	}
}
